package expertise.resume.impl.stringify;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
import com.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy;
import com.itextpdf.text.pdf.parser.TextExtractionStrategy;

import expertise.resume.ResumeStringifier;
import expertise.resume.exception.ResumeStringifyException;

@Component
public class PdfResumeStringifier implements ResumeStringifier {

	private static final Logger log = Logger.getLogger(PdfResumeStringifier.class);

	@Override
	public String stringifyResume(final InputStream inputStream) throws ResumeStringifyException {
		try {
			ByteArrayOutputStream buffer = new ByteArrayOutputStream();
			PrintWriter printWriter = new PrintWriter(buffer);

			PdfReader reader = new PdfReader(inputStream);
			PdfReaderContentParser contentParser = new PdfReaderContentParser(reader);

			TextExtractionStrategy strategy;
			for (int i = 1; i <= reader.getNumberOfPages(); i++) {
				strategy = contentParser.processContent(i, new SimpleTextExtractionStrategy());
				printWriter.append(strategy.getResultantText());
			}

			printWriter.close();

			return buffer.toString();
		} catch (IOException e) {
			e.printStackTrace();
			throw new ResumeStringifyException("IO Issue Stringifying PDF", e);
		} finally {
			try {
				inputStream.close();
			} catch (IOException e) {
				log.error("Issue closing input stream containing resume pdf data", e);
			}
		}
	}

}
